package com.haiheng.library_base.dialog;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.haiheng.library_base.R;

/**
 * @Des:
 * @Author: hwz
 * @Date:2022/7/13 0013
 * @Version: 1.0
 */
public class GifLoadingDialog {
    Dialog mLoadingDialog;
    ImageView iv_loading_gif;
    private static GifLoadingListener gifLoadingListener;

    public GifLoadingDialog(Context context) {
        // 获取视图
        View view = LayoutInflater.from(context).inflate(R.layout.loading_layout, null);
        // 获取整个布局
        LinearLayout layout = (LinearLayout) view.findViewById(R.id.ll_loading_container);
        iv_loading_gif = view.findViewById(R.id.iv_loading_gif);

//        Glide.with(context).load(R.drawable.loading).into(iv_loading_gif);

        mLoadingDialog = new Dialog(context, R.style.loading_dialog);
        // 设置返回键无效
        mLoadingDialog.setCancelable(true);
        mLoadingDialog.setCanceledOnTouchOutside(true);
        mLoadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        WindowManager.LayoutParams lp = mLoadingDialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;
        lp.width = context.getResources().getDimensionPixelOffset(R.dimen.dp_365);//修复宽度问题
        mLoadingDialog.getWindow().setAttributes(lp);
    }

    /**
     * 显示加载框
     */
    public void show() {
        if (mLoadingDialog.isShowing()) {
            return;
        }
        if (gifLoadingListener != null) {
            gifLoadingListener.show();
        }
        performAnimate();
        mLoadingDialog.show();

    }


    /**
     * 隐藏加载框
     */
    public void hide() {
        if (gifLoadingListener != null) {
            gifLoadingListener.hide();
        }
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            performAnimate();
            mLoadingDialog.dismiss();
        }
    }

    /**
     * 执行gif动画
     */
    private void performAnimate() {
//        if (iv_loading_gif != null && iv_loading_gif.getDrawable() instanceof GifDrawable) {
//            GifDrawable drawable = (GifDrawable) iv_loading_gif.getDrawable();
//            if (!drawable.isRunning()) {
//                drawable.start();
//            } else {
//                drawable.stop();
//            }
//        }
    }


    public interface GifLoadingListener {
        void show();

        void hide();
    }

    public static void setGifLoadingListener(GifLoadingListener gifLoadingListener) {
        GifLoadingDialog.gifLoadingListener = gifLoadingListener;
    }

}
